package jishiti;

import org.junit.Test;

import java.util.*;

public class DeleteIterator {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        Iterator <Integer> it = list.iterator();
        while (it.hasNext()){
            it.next();//迭代器删的很干净，但是必须先有it.next()
          it.remove();//否则报错IllegalStateException
        }
       list.forEach(System.out::println);
     }
     @Test
    public void say(){
        Map<Integer,String> map = new HashMap<>();
        map.put(32,"aa");
        map.put(21,"bb");
        map.put(34,"cc");
        map.put(42,"ee");
        map.put(87,"er");
        Iterator<Map.Entry<Integer,String>> it = map.entrySet().iterator();
        while (it.hasNext()){
            it.next();//迭代器删除必须加it.next()，否则报错IllegalStateException
            it.remove();
        }
         map.entrySet().forEach(System.out::println);//迭代器能删干净
     }
     @Test
    public void filterStr (){
        List<String> list = new ArrayList<>();
        list.add("DELdd");
        list.add("DELdda");
        list.add("daf");
        String str =null;
//         for (int i = 0; i <list.size(); i++) {//i从0开始删，因为删除元素会造成下标改变，
//             str = list.get(i);//如果两个连续的元素符合删除条件，就会因为下标改变而漏删。
//             if (str.startsWith("DEL")){
//                 list.remove(str);
//             }
//         }
         for (int i = list.size()-1; i >=0; i--) {//改成i从最大下标开始遍历，就不会删不干净了
             str = list.get(i);
             if (str.startsWith("DEL")){
                 list.remove(str);
             }
         }
         list.forEach(System.out::println);
         System.out.println(list);
     }
}
